#!/usr/bin/env python
# -*- coding:utf-8 -*- 
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:

"""
@version: 1.0
@author: readerror
@contact: readerror@readerror.cn
@contact1: readerror000@gmail.com
@site: http://www.readerror.cn
@software: PyCharm
@file: system.py
@time: 2017/3/22 10:23
"""

from .. import errors


def environment_variables_init(client):
    """
    查询系统必须的环境uuid

    :param client: ZStack RESTFul API client
    :return:{
        'cluster_uuid': 第一个集群的uuid,
        'zone_uuid': 第一个zone的uuid,
        'services': L3网络服务list,
        'vrouter_image_uuid': 第一个云路由镜像uuid,
        'no_vlan_l3_network_uuid': 第一个NoVlanL3网络uuid（公共网络）
    }
    """
    # 取第一个集群的uuid
    try:
        clusters = client.query_cluster(data={'fields': ['uuid']})
        assert len(clusters), errors.ZStackException('Cluster greater than 1')
        cluster_uuid = clusters[0]['uuid']
    except IndexError:
        raise errors.ZStackException('Cluster not found')

    # 取第一个zone的uuid
    try:
        zones = client.query_zone(data={'fields': ['uuid']})
        assert len(zones), errors.NullResource('Zone greater than 1')
        zone_uuid = zones[0]['uuid']
    except IndexError:
        raise errors.ZStackException('Zone not found')

    # 取L3网络服务list
    res = client.query_network_service_provider(data={
        'count': False,
        'replyWithCount': True,
        'start': 0})
    services = {'all': []}
    for service in res:
        service_type = service.get('type')
        if services.get(service_type) is not None:
            raise errors.ZStackException('Network service types error')
        services[service_type] = {
            'uuid': service['uuid'],
            'networkServiceTypes': service.get('networkServiceTypes')}
        services['all'].append(service_type)

    # 取第一个云路由镜像uuid
    try:
        vrouter_images = client.query_image(data={'conditions': [{'name': 'system', 'op': '=', 'value': 'true'}]})
        assert len(vrouter_images), errors.ZStackException('VRouter image  greater than 1')
        vrouter_image_uuid = vrouter_images[0]['uuid']
    except IndexError:
        raise errors.ZStackException('VRouter image not found')

    # 取第一个NoVlanL3网络uuid
    try:
        no_vlan_l2_networks = client.query_l2_network(data={
            'conditions': [{'name': 'type', 'op': '=', 'value': 'L2NoVlanNetwork'}], 'fields': ['uuid']})
        assert len(no_vlan_l2_networks), errors.ZStackException('NOVlan l2 networks  greater than 1')
        no_vlan_l2_network_uuid = no_vlan_l2_networks[0]['uuid']
    except IndexError:
        raise errors.ZStackException('NoVlan L2 network not found')

    # 取第一个NoVlanL3网络uuid
    try:
        no_vlan_l3_networks = client.query_l3_network(data={
            'conditions': [{'name': 'l2NetworkUuid', 'value': no_vlan_l2_network_uuid, 'op': '='}], 'fields': ['uuid']})
        no_vlan_l3_network_uuid = no_vlan_l3_networks[0]['uuid']
    except IndexError:
        raise errors.ZStackException('NoVlan L3 network not found')

    return {'cluster_uuid': cluster_uuid,
            'zone_uuid': zone_uuid,
            'services': services,
            'vrouter_image_uuid': vrouter_image_uuid,
            'no_vlan_l3_network_uuid': no_vlan_l3_network_uuid}


def share_resource2user(client, username, resource_uuids, async=False):
    if resource_uuids is str:
        resource_uuids = [resource_uuids]
    data = {'conditions': [{'name': 'name', 'value': username, 'op': '='}]}
    user_info = client.query_account(data)[0]
    user_uuid = user_info.get('uuid')
    rsp = client.share_resource({'accountUuids': [user_uuid], 'resourceUuids': resource_uuids}, async=async)
    client.log.info('[ZStack for OSYL] Share resource[%s] to user[%s] succeed' % (resource_uuids, username))
    return rsp


def share_resource_public(client, resource_uuids, public, async=False):
    if resource_uuids is str:
        resource_uuids = [resource_uuids]
    data = {'resourceUuids': resource_uuids, 'toPublic': True}
    if not public:
        data['all'] = True
    rsp = client.share_resource(data, async=async)
    client.log.info('[ZStack for OSYL] %s resource[%s] form all succeed' %
                    ('Share' if public else 'Recycle', resource_uuids))
    return rsp


def query_host(client):
    """
    查询cpu、内存

    :param client:
    :return:
    """
    return client.query_host()


def query_primary_storage(client):
    """
    查询主存储

    :param client:
    :return:
    """
    return client.query_primary_storage()


def query_backup_storage(client):
    """
    查询镜像服务器

    :param client:
    :return:
    """
    return client.query_backup_storage()
